<template>
    <Header title="登录" leftArrow="true" @onBarClickLeft="goHome"/>
    <div class="body">
      <div class="container">
        <div>
            <label for="user_name" class="field">用户名:</label>
            <input v-model="userData.user_name" id="user_name" type="text" placeholder="请输入用户名">
        </div>
         <div>
            <label for="password" class="field">密码:</label>
            <input v-model="userData.password" id="password" type="password" placeholder="请输入密码">
        </div>
        <div>
            <button @click="doLogin" >登录</button>
            <a href="" @click="goToRegist">去注册</a>
        </div>
    </div>
    </div>
</template>

<script>
import { login } from "../api/user"
import { TOKEN_NAME } from "../utils/const"
import {useRouter} from 'vue-router'
import {useStore} from 'vuex'
import { Toast } from "vant/es/toast"
import "vant/es/toast/style"
import Header from "../components/Header.vue"

export default {
    components: {
        Header,
    },
    setup() {
        //useRouter  useStore 只能在setup里面使用，不能再其他函数中使用
        const router = useRouter()
        const store = useStore()
        const userData = {
            user_name: '',
            password: ''
        }

        function doLogin(){
            login(userData).then((res)=>{
                if(res.code == 0){
                   Toast(res.message)
                   //把token保存在localstorage中,当请求的时候在header中带上
                   localStorage.setItem(TOKEN_NAME, res.result.token)
                   store.commit('setUserInfo', res.result)
                 // store.dispatch('setUserInfo', res.result)
                   router.push("/")
                } else {
                   console.log("login error", res.message);
                }
            })
        }

        function goToRegist(){
            router.push('regist')
        }

        const goHome = () => {
             router.push('/')
        }

        return {
            userData,
            doLogin,
            goHome,
            goToRegist
        }
    },
}
</script>

<style scoped>

.body{
    
}
.container{
    font-size: 15px;
    margin:0 auto;
	

    background: rgb(153, 224, 180);
    overflow:hidden;/**  超出盒子的部分就隐藏 */
}

.container div{
    margin: 20px auto;
    display: flex;
    justify-content: center;
}

.field{
    flex: 0 0 120px;
    text-align: right;
}
a{
    height: 40px;
    line-height: 40px;
    margin-left:30px;
}
</style>
